package com.knowswift.issues.controller;

import com.baomidou.mybatisplus.extension.api.R;
import com.knowswift.common.bean.issue.po.Customer;
import com.knowswift.common.bean.issue.po.SysUser;
import com.knowswift.common.bean.issue.vo.ModuleDto;
import com.knowswift.common.bean.project.po.Project;
import com.knowswift.log.aop.AopLog;
import com.knowswift.security.util.AllowVisitor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;

/**
 * @author CTL
 * @create 2025-07-24 16:21
 */
@RestController
@RequestMapping("/sysuser")
public class SysUserController  extends AbstractController{

    //@AopLog(saveLog = false, name = "查询客户详情", platform = "管理后台")
    @GetMapping("/info/{userId}")
    @AllowVisitor(checkToken = false)
    public R info(@PathVariable("userId") Long userId) {
        SysUser user = sysUserService.getById(userId);
        if(user==null){
            return R.failed("未查询到id为"+userId+"的客户账户");
        }
        //获取客户账户授权项目
        List<ModuleDto> moduleDtoList = authorizeService.getBaseMapper().getModuleByUserId(userId);
        for (ModuleDto module : moduleDtoList) {
            List<Project> projectList = authorizeService.getBaseMapper().getUserModuleProject(userId, module.getModuleId());
            module.setProjects(projectList);
        }
        user.setModuleList(moduleDtoList);
        return R.ok(user);
    }



    @AopLog(saveLog = false, name = "新增客户", platform = "管理后台")
    @PostMapping("/save")
    @AllowVisitor(checkToken = false)
    public R save(@Valid @RequestBody SysUser user) {
        sysUserService.save(user);
        return R.ok("新增成功");
    }

    @AopLog(saveLog = false, name = "修改客户", platform = "管理后台")
    @PostMapping("/update")
    @AllowVisitor(checkToken = false)
    public R update(@Valid @RequestBody SysUser user) {

        sysUserService.updateById(user);
        return R.ok("修改成功");
    }

    @AopLog(saveLog = false, name = "删除客户", platform = "管理后台")
    @DeleteMapping("/delete")
    @AllowVisitor(checkToken = false)
    public R delete(@RequestBody Long[] userIds) {
        sysUserService.removeByIds(Arrays.asList(userIds));
        return R.ok("删除成功");
    }
    @AopLog(saveLog = false, name = "授权客户项目", platform = "管理后台")
    @PostMapping("/Auth")
    @AllowVisitor(checkToken = false)
    public R ProjectAuthorize(@RequestParam Long userId, @RequestBody List<ModuleDto> moduleList){
        SysUser user = sysUserService.getById(userId);
        if(user==null){
            return R.failed("未查询到id为"+user+"的客户账户");
        }
        sysUserService.ProjectAuthorize(userId,moduleList);
        return R.ok("授权成功");
    }

}
